const _ = require('lodash');
const async = require('async');
const services = require('../services');
const enums = require('../enums');
const soag = require('../modules/lilly-soag');

const commonService = services.common;

function login(req, res, callback) { // eslint-disable-line
  res.redirect('/auth/ping');
}

function logoff(req, res, callback) {
  req.logout();
  req.session.destroy();
  callback();
}

function getCurrentUser(req, res, callback) {
  if (_.isEmpty(req.user)) return callback(commonService.getError(enums.errorCode.unauthorized));
  const employeeId = req.user.employeeId;
  const { SysUser: userModel } = commonService.getModels();
  const getUser = (next) => {
    commonService.getDetail(userModel, { where: { employeeId, status: 0 }, include: ['lineManager', 'department', 'roleList'] }, next);
  };
  async.waterfall([getUser], callback);
}

function getDetailByName(req, res, callback) {
  const params = req.query;
  const roleName = params.roleName;
  const { SysRole: roleModel } = commonService.getModels();
  const getDetailByName = (next) => {
    commonService.getDetail(roleModel, { where: { name: roleName } }, next);
  };
  async.waterfall([getDetailByName], callback);
}

function getUserListByEmployeeIds(req, res, callback) {
  const employeeIds = req.query.employeeIds;
  const { SysUser: userModel } = commonService.getModels();
  const employeeIdArray = employeeIds.split(',');
  const getUserListByEmployeeIds = (next) => {
    commonService.getList(userModel, { where: { employeeId: { inq: employeeIdArray } }, include: ['roleList'] }, next);
  };
  async.waterfall([getUserListByEmployeeIds], callback);
}

function getFormList(req, res, callback) {
  const { WfForm: formModel } = commonService.getModels();
  commonService.getList(formModel, callback);
}

function sendEmailReminder(req, res, callback) {
  services.eLanco.sendEmailReminder();
  callback();
}


module.exports = {
  login,
  logoff,
  getCurrentUser,
  getDetailByName,
  getUserListByEmployeeIds,
  getFormList,
  sendEmailReminder,
};
